package com.dgut.ibeacon.controller;


import com.dgut.ibeacon.constants.UserConstants;
import com.dgut.ibeacon.entity.AjaxResult;
import com.dgut.ibeacon.entity.Role;
import com.dgut.ibeacon.entity.User;
import com.dgut.ibeacon.service.IRoleService;
import com.dgut.ibeacon.service.IUserService;
import com.dgut.ibeacon.shiro.service.SysPasswordService;
import com.dgut.ibeacon.utils.core.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuec
 * @since 2020-10-14
 */
@RestController
@RequestMapping("//user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @Autowired
    private SysPasswordService sysPasswordService;


    /**
     * 登录
     * @param username
     * @param password
     * @param rememberMe
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return AjaxResult.success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return AjaxResult.error(msg);
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult ajaxRegister(User user){

        user.setPassword(sysPasswordService.encryptPassword(user.getLoginName(), UserConstants.DEFAULT_PASSWORD, ""));
        Map map=new HashMap();
        map.put("user_name",user.getUserName());
        int size=userService.listByMap(map).size();
        if (size>=1){
            return AjaxResult.error("账号名已存在！");
        }
        if(userService.save(user)==true){
            Role role=new Role();
            role.setUserId(((User)userService.listByMap(map).get(0)).getUserId());
            role.setRole(Integer.valueOf(UserConstants.NORMAL));
            roleService.save(role);
            return AjaxResult.success("账号创建成功！");
        }else {
            return AjaxResult.error("创建失败！");
        }
    }



}
